﻿using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Text;

namespace FileSubscriptionServer.Helpers
{
    public static class FileManager
    {
        public static List<WatchItem> Watchs = new List<WatchItem>();

        public static void AddWatch(string watch, string id = null)
        {
            if(string.IsNullOrEmpty(id))
                id = Guid.NewGuid().ToString();

            if (Watchs.Any(n => string.Equals(n.Id, id)))
                throw new NotSupportedException();

            Watchs.Add(new WatchItem
            {
                Id = id,
                Watch = watch,
            });
        }

        public static List<WatchItem> GetWatches()
        {
            return Watchs;
        }

        public static string GetMD5HashFromFile(string fileName)
        {
            try
            {
                FileStream file = new FileStream(fileName, System.IO.FileMode.Open);
                MD5 md5 = new MD5CryptoServiceProvider();
                byte[] retVal = md5.ComputeHash(file);
                file.Close();
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < retVal.Length; i++)
                {
                    sb.Append(retVal[i].ToString("x2"));
                }
                return sb.ToString();
            }
            catch (Exception ex)
            {
                //return ex.Message;
                Console.WriteLine(ex);
                return null;
            }
        }

        public static string? GetPath(string id, string path)
        {
            var watch = GetWatches()?.FirstOrDefault(n => id == n.Id);
            if (watch == null)
                return null;

            if (string.IsNullOrEmpty(path))
                return watch.Watch;

            var newPath = path.Replace("/", "\\");
            if(newPath.StartsWith("\\"))
                newPath = newPath.Substring(1);

            if (Path.GetFullPath(path) == path)
                throw new Exception($"不允许的路径");

            return Path.Combine(watch.Watch, newPath);
        }

        public static string? GetRelativePath(string id, string path)
        {
            var watch = GetWatches()?.FirstOrDefault(n => id == n.Id);
            if (watch == null)
                return null;

            if (string.IsNullOrEmpty(path))
                return watch.Watch;

            if (path.StartsWith(watch.Watch) != true)
                throw new NotSupportedException();

            return path.Substring(watch.Watch.Length);
        }
    }

    public class WatchItem
    {
        public string Id { get; set; }

        public string Watch { get; set; }
    }
}
